﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CNav.Business.Services;
using CNav.Common;
using CNav.Domain;
using CNav.Domain.Admin;
using CNav.Support;
using WebGrease.Css.Extensions;

namespace CNav.Controllers
{
    [Authorize]
    [AdminAuthorize]
    public class FormConfigController : BaseController
    {
        public ActionResult Index()
        {
            var responseData = Service.Get<IAdminConfigurationService>().GetFormConfigurationList();
            PopulateUiControls();

            return View(responseData.Data);
        }

        public ActionResult Edit()
        {
            var responseData = Service.Get<IAdminConfigurationService>().GetFormConfigurationList();
            PopulateUiControls();

            return View(responseData.Data);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(IEnumerable<FormConfiguration> formConfigurations)
        {
            if (ModelState.IsValid)
            {
                var formConfigs = formConfigurations.Where(f => f.FormID != -1).ToList();
                var response = Service.Get<IAdminConfigurationService>().UpdateFormConfiguration(formConfigs);
                if (response.Error == null)
                    return RedirectToAction("Index");

                response.Error.ForEach(e => ModelState.AddModelError("", e));
            }

            var responseData = Service.Get<IAdminConfigurationService>().GetFormConfigurationList();
            PopulateUiControls();

            return View(responseData.Data);
        }

        private void PopulateUiControls()
        {
            var responseDataSourceList = Service.Get<IUiService>().GetFormList();
            responseDataSourceList.Data.Insert(0, new Form{ID=-1, Name= "Select form"});
            ViewBag.FormList = responseDataSourceList.Data;
        }
    }
}
